package com.HardWare;

import com.friendlyarm.AndroidSDK.HardwareControler;

/**
 * Created by Ziji on 2017/7/13.
 */

public class HMC5883
{
    public static final double MAGNETIC=1.3;
        static int HMC5883_Init(int devFD)
        {
            HardwareControler.setI2CSlave(devFD,(byte)(0x1E));//设置I2c通信硬件地址
            if(HardwareControler.I2CWriteByteData(devFD,(byte)0x02, (byte) 0x00,0)>=0)
            {
                return 0;
            }
            return -1;
        }
        static short[] readHMC5883_X(int devFD)
        {
            byte[] data;
            data=new byte[6];
            HardwareControler.I2CWriteByteData(devFD,(byte)0x02, (byte) 0x01,0);
            for(int i=0;i<6;i++) {
                data[i]=(byte)HardwareControler.I2CReadByteData(devFD,0x03+i,0);
            }
            short[] data_16;
            data_16 = new short[3];
            for(int i=0;i<3;i++)
            {
                data_16[i]=change_8to16(data[2*i],data[2*i+1]);
            }
            return data_16;
        }

        static short change_8to16(byte x,byte y)
        {
            short m;
            m= (short) (((short)x<<8)+(short)y);
            if(m==-4096)
            {
                m=-2048;
            }
            return m;
        }

        static double[] get_magnetic(int devFD)
        {
            short[] data;
            data=readHMC5883_X(devFD);
            double[] data_magnetic;
            data_magnetic=new double[3];
            for (int i=0;i<3;i++)
            {
                data_magnetic[i]=MAGNETIC/2047*data[i];
            }
            return data_magnetic;
        }

}